from flask import Flask, request, jsonify
import time
import hashlib
import json

app = Flask(__name__)

def get_md5(s):
    md5 = hashlib.md5()
    md5.update(s.encode('utf-8'))
    return md5.hexdigest()
@app.before_request
def before():
    if 'login' in request.path:
        #1.验证时间不能拖太久，取出当前时间减去传入的时间
        ctime = time.time()
        #取出app传入的时间
        in_ctime = int(request.headers.get('ctime'))
        if ctime - in_ctime >1000:
            return jsonify({'code':109,'msg':"该请求已失效"})

@app.route('/login',methods=['POST'])
def login():

    #2.验证签名是否正确
    sign = request.form.get('sign')
    username = request.form.get("username")
    password = request.form.get("password")
    new_sign = get_md5(username + 'jkwang')
    if new_sign == sign:
        print("请求来了")

        if username == "admin" and password == "e10adc3949ba59abbe56e057f20f883e":
            #返回给前端json格式数据
            return jsonify({"code": 201, "msg": "登录成功ss"})
        else:
            return jsonify({"code": 101, "msg": "失败"})
    else:
        return jsonify({"code": 102, "msg": "失败,签名不对 "})

@app.route('/films',methods=['GET'])
def films():
    with open('./films.json','r',encoding="utf-8") as f:
        films_dict = json.load(f)
    return jsonify(films_dict)


#运行app
if __name__ == '__main__':
    app.run("0.0.0.0", 1022)